<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Job\WalletAddJob;
use App\Fastapp\Model\Account;
use App\Fastapp\Model\AccountWallet;
use App\Fastapp\Model\FastappAppSetting;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Mine\Exception\NormalStatusException;

/**
 * 应用设置列表Mapper类
 */
class FastappAppSettingMapper extends AbstractMapper
{
    /**
     * @var FastappAppSetting
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappAppSetting::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['name']) && filled($params['name'])) {
            $query->where('name', 'like', '%' . $params['name'] . '%');
        }

        if (isset($params['account_type']) && filled($params['account_type'])) {
            $query->where('account_type', 'like', '%' . $params['account_type'] . '%');
        }

        if (isset($params['key']) && filled($params['key'])) {
            $query->where('key', 'like', '%' . $params['key'] . '%');
        }

        return $query;
    }

    public function save(array $data): mixed
    {
        if ($data['key'] == 'symbol') {
            foreach (explode(',', $data['val']) as $v) {
                if (empty(get_currency_cache($v))) throw new NormalStatusException($v . '无效');
            }
        }
        $s = parent::save($data);
        api_cache()->clearAppSetting($data['account_type']);
        return $s;
    }

    public function update(mixed $id, array $data): bool
    {
        if ($data['key'] == 'symbol') {
            foreach (explode(',', $data['val']) as $v) {
                if (empty(get_currency_cache($v))) throw new NormalStatusException($v . '无效');
            }
        }
        $s = parent::update($id, $data);
        api_cache()->clearAppSetting($data['account_type']);
        return $s;
    }

    public function walletSync(array $params): bool
    {
        $uid = Account::query()->where(['type' => $params['account_type']])->orderBy('id')->value('gene_id');
        $exist = AccountWallet::query()->where(['user_id' => $uid])->pluck('symbol')->toArray();
        $symbols = array_diff(explode(',', $params['val']), $exist);
        foreach ($symbols as $symbol) {
            fastapp_queue_push(new WalletAddJob(0, $params['account_type'], $symbol));
        }
        return true;
    }

    public function currency(int $account_type): array
    {
        $symbol = $this->model::query()->where(['account_type' => $account_type, 'key' => 'symbol'])->value('val');
        $list = [];
        if ($symbol) {
            foreach (explode(',', $symbol) as $v)
                $list[] = [
                    'label' => $v,
                    'value' => $v
                ];
        }
        return $list;
    }
}